package cn.wh.executor;

import cn.wh.executor.statement.StatementHandler;
import cn.wh.mapping.BoundSql;
import cn.wh.mapping.MappedStatement;
import cn.wh.session.Configuration;
import cn.wh.session.ResultHandler;
import cn.wh.session.RowBounds;
import cn.wh.transaction.Transaction;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @Author wh
 * @Description 简单执行器
 * @Date 2023/1/18 11:23
 * @Version 1.0
 **/
public class SimpleExecutor  extends BaseExecutor {
    public SimpleExecutor(Configuration configuration, Transaction transaction) {
        super(configuration, transaction);
    }

    @Override
    protected <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        try{
            Configuration configuration = ms.getConfiguration();
            StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, rowBounds, resultHandler, boundSql);
            Connection connection = transaction.getConnection();
            Statement stmt = handler.prepare(connection);
            handler.parameterize(stmt);
            return handler.query(stmt,resultHandler);
        }catch (SQLException e){
           e.printStackTrace();
           return null;
        }
    }

    @Override
    protected int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
        Statement stmt=null;
        try{
            Configuration configuration = ms.getConfiguration();
            //新建一个 StatementHandler
            StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
            //准备语句
            stmt=prepareStatement(handler);
            return handler.update(stmt);
        }finally {
            closeStatement(stmt);
        }

    }

    private Statement prepareStatement(StatementHandler handler)throws SQLException{
        Statement stmt;
        Connection connection = transaction.getConnection();
        //准备语句
        stmt=handler.prepare(connection);
        handler.parameterize(stmt);
        return stmt;
    }


}
